const UserService = require('../services/UserService')
const {
  verifyPwd,
  encrypted,
  createToken,
  varifyToken
} = require('../utils/utils')
const { detailAvatar } = require("../services/AvatarService");
const AVATAR_PATH = '../upload';
const path = require('path')
const fs = require('fs')
module.exports = {
  // login
  login: async (ctx) => {
    const {
      username,
      password
    } = ctx.request.body
    // console.log(ctx.request.body)
    if (!username || !password) {
      ctx.body = {
        code: 10001,
        msg: '用户名与密码不能为空'
      }
      return
    }
    const count = await UserService.getUserByUserName(username)
    
    if (count.length > 0) {
      const encryPwd = count[0].dataValues.password
      const userInfo = count[0].dataValues
      const flag = await verifyPwd(password, encryPwd)
      const token = createToken(userInfo)
      delete userInfo.password
      if (flag) {
        ctx.body = {
          code: 200,
          msg: '登录成功',
          data: {
            ...userInfo,
            token
          }
        }
      } else {
        ctx.body = {
          code: 10001,
          msg: '密码错误'
        }
      }
    } else {
      ctx.body = {
        code: 10001,
        msg: '请检查账户名'
      }
    }
  },
  logout: async (ctx) => {
    ctx.body = {
      code: 200,
      msg: '已成功退出',
      data: null
    }
  },
  // 注册、添加用户
  addUser: async (ctx) => {
    const user = ctx.request.body
    if (!user.nickname) {
      user.nickname = '新用户'
    }
    const count = await UserService.getUserByUserName(user.username)
    const phone = await UserService.getUserByPhone(user.phone)
    if (count.length > 0) {
      ctx.body = {
        code: 10001,
        msg: '当前用户名已存在'
      }
    } else if (phone.length > 0) {
      ctx.body = {
        code: 10001,
        msg: '当前手机号码已注册'
      }
    } else {
      user.password = await encrypted(user.password)
      const result = await UserService.createUser(user)
      delete result.password
      if (result) {
        ctx.body = {
          code: 200,
          msg: '注册成功'
        }
      } else {
        ctx.body = {
          code: 10001,
          msg: '注册失败'
        }
      }
    }
  },
  
  getUserList: async ctx => {
    const params = ctx.query
    const {
      count,
      rows
    } = await UserService.getUserList(params)
    if (count > 0) {
      const userList = []
      for (let i = 0; i < rows.length; i++) {
        const data = rows[i].dataValues
        userList.push(data)
      }
      ctx.body = {
        code: 200,
        msg: '获取成功',
        data: {
          list: userList,
          total: count,
          limit: 10
        }
      }
    }
  },
  // 更新
  updateUser: async (ctx) => {
    const data = ctx.request.body
    const count = await UserService.getUserById(data.id)
    if (count.length > 0) {
      if (data.password) {
        data.password = await encrypted(data.password)
      }
      const result = await UserService.updateUser(data.id, data)
      if (result[0] === 1) {
        ctx.body = {
          code: 200,
          msg: '更新账户信息成功',
        }
      } else {
        ctx.body = {
          code: 10001,
          msg: '更新账户信息失败',
        }
      }
    } else {
      ctx.body = {
        code: 10001,
        msg: '不存在此id用户',
      }
    }
  },
  resetPassword: async (ctx) => {
    const data = ctx.request.body
    const count = await UserService.getUserByPhone(data.phone)
    if (count.length > 0) {
      if (data.code !== '123456') {
        ctx.body = {
          code: 10001,
          msg: '验证码不正确',
        }
        return
      }
      if (data.password) {
        data.password = await encrypted(data.password)
      }
      const result = await UserService.updateUser(count[0].id, {
        password: data.password
      })
      if (result[0] === 1) {
        ctx.body = {
          code: 200,
          msg: '重置密码成功',
        }
      } else {
        ctx.body = {
          code: 10001,
          msg: '重置密码失败',
        }
      }
    } else {
      ctx.body = {
        code: 10001,
        msg: '不存在此id用户',
      }
    }
  },
  updatePassword: async (ctx) => {
    const data = ctx.request.body
    const count = await UserService.getUserById(data.id)
    if (count.length > 0) {
      const oldPassword = await encrypted(data.oldPassword)
      if (oldPassword !== result[0].password) {
        ctx.body = {
          code: 10001,
          msg: '请输入正确的旧密码',
        }
        return
      }
      if (data.password) {
        data.password = await encrypted(data.password)
      }
      const result = await UserService.updateUser(data.id, {
        password: data.password
      })
      if (result[0] === 1) {
        ctx.body = {
          code: 200,
          msg: '修改密码成功',
        }
      } else {
        ctx.body = {
          code: 10001,
          msg: '修改密码失败',
        }
      }
    } else {
      ctx.body = {
        code: 10001,
        msg: '不存在此id用户',
      }
    }
  },
  // 删除
  deleteUser: async (ctx) => {
    const {id} = ctx.request.body
    const count = await UserService.getUserById(id)
    let token = ctx.request.headers['authorization']
    const tokenInfo = await varifyToken(token)
    const userInfo = tokenInfo.userInfo
    if (count.length > 0) {
      if (parseInt(userInfo.id) === parseInt(count[0].dataValues.id)) {
        ctx.body = {
          code: 10001,
          msg: '不可删除自己',
          data: null
        }
      } else {
        const result = await UserService.deleteUser(id)
        if (result === 1) {
          ctx.body = {
            code: 200,
            msg: '删除成功',
          }
        } else {
          ctx.body = {
            code: 10001,
            msg: '删除失败',
          }
        }
      }
    } else {
      ctx.body = {
        code: 10001,
        msg: '此id用户不存在',
      }
    }
  },
  // 获取用户信息，在 token 中携带
  getUserInfo: async (ctx) => {
    let token = ctx.request.headers['authorization']
    const tokenInfo = await varifyToken(token)
    // console.log(tokenInfo)
    const userInfo = tokenInfo.userInfo
    if (tokenInfo) {
      delete userInfo.password
      ctx.body = {
        code: 200,
        msg: '登录成功',
        data: {
          userInfo
        }
      }
    }
  },
  
  // 获取用户信息
  getUserInfoById: async (ctx) => {
    const {userId} = ctx.request.params
    const count = await UserService.getUserById(userId)
    const userInfo = count[0].dataValues
    if (count.length > 0) {
      ctx.body = {
        code: 200,
        msg: '登录成功',
        data: userInfo
      }
    }
  },

  getUserAvatar: async (ctx) => {
    const { userId } = ctx.params;
    // 从数据库中获取当前图片的详情信息。然后用于本地获取图片。
    const count = await detailAvatar(userId);
    if (count.length > 0) {
      const avatarInfo = count[0].dataValues
      // 2.提供图像信息,以便浏览器解析
      ctx.response.set('content-type', avatarInfo.mimetype);
      ctx.body = fs.createReadStream(path.resolve(__dirname, `${AVATAR_PATH}/${avatarInfo.filename}`));
    } else {
      ctx.body = {
        code: 10001,
        msg: '暂未配置头像'
      }
    }
  }
}
